<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Goods;
use App\Models\Author;
use App\Models\GoodsCategory;
use App\Models\GoodsCollection;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\Goods as GoodsModel;
use App\Models\Author as AuthorModel;
use App\Admin\Renderable\AuthorTable;
use Illuminate\Support\Facades\Redis;

class GoodsController extends AdminController
{
//    public function index(Content $content)
//    {
//        return $content->body(new GoodsTable());
//    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Goods(['goodsCategory','authors']), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('name')->width("15%");
            $grid->column('short_name')->editable();
            $grid->column("goodsCategory.name", "商品类别");
            $grid->column('click_number')->sortable();
            $grid->column("integral")->editable()->sortable();
            $grid->column("flash_sale_price", "秒杀价")->editable()->sortable();
            $grid->column("price", "价格")->editable()->sortable();
//            $grid->column("promote_price","特惠价格")->editable()->sortable();
            $grid->column("sku", "库存")->editable()->sortable();
            $grid->column("order_number")->editable()->sortable();
            $grid->column("is_seckill")->bool();
            $grid->column("created_at", "上传时间")->sortable();
//            $grid->column("on_sale","是否在售")->switch(1,true);
            // 不写label会自动从翻译文件翻译，具体使用请参照 “字段翻译” 章节
            $grid->column('状态组')->switchGroup(["on_sale", 'is_new', 'is_recommend']);
            // 也可以这样
            $grid->disableBatchDelete();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                // append一个操作 这里呢就是屏蔽原有的详情，加一个PC、手机端的详情
                $actions->disableView();
                $actions->row->id;//当前列的id
                $actions->append('<a href=""><i class="fa fa-eye"></i>显示</a>');

                $url = <<<URL
/cpgdeal/collection_users?goods_id={$actions->row->id}
URL;
                $count = GoodsCollection::where("goods_id", $actions->row->id)->count();
                $actions->append('<a href="' . $url . '"><i class="fa fa-heart"></i>收藏人列表(' . $count . ')</a>');
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('name');
                $filter->equal('goods_category_id', "商品类别")
                    ->select(GoodsCategory::pluck("name", "id")->toArray());
                $filter->equal("authors.id", "作家")
                    ->selectTable(AuthorTable::make())
                    ->title("作家")
                    ->model(Author::class, 'id', "name");
                $filter->between('created_at', "添加日期")->datetime();

                $filter->equal("on_sale", "是否在售")
                    ->select([
                        1 => "是",
                        0 => "否"
                    ]);
//                $filter->equal("is_hot","是否特惠")
//                    ->select([
//                        1=>"是",
//                        0=>"否"
//                    ]);
                $filter->equal("is_new", "是否最新")
                    ->select([
                        1 => "是",
                        0 => "否"
                    ]);
                $filter->equal("is_recommend", "是否推荐")
                    ->select([
                        1 => "是",
                        0 => "否"
                    ]);
                $filter->equal("is_seckill")
                    ->select([
                        1 => "是",
                        0 => "否"
                    ]);


            });
            $titles = ["id"=>"ID","name"=>"名称","click_number"=>"点击量"];
            $grid->export($titles);
            // 只导出 id, name和email 三列数据
        });

    }


    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
//        //这里，链接，放前端的链接
//        $model = GoodsModel::with("goods_content","goods_images","goods_category");
//        return Show::make($id, $model, function (Show $show) {
//            $show->field('id');
//            $show->field('name');
//            $show->field('goods_category.name');
//            $show->img()->image();
//            $show->field("goods_content.content","内容");
//
//
//        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Goods(["goodsContent", "goodsImages", "authors"]), function (Form $form) {
            $form->tab("基础信息", function (Form $form) {
                $form->text('name')->required()->rules(function ($form) {
                    return "unique:goods,name," . $form->model()->id;
                });
                $form->text('short_name')->required()->help("纯商品名，不要加作者，用于购物券显示");
                $form->text('long_title');
                $form->text("tags");
                $form->text("spec");
                $form->text("price");
                $form->number("sku");
                $form->number("order_number");
//                $form->number("stars","推荐等级")
//                    ->default(5)
//                    ->rules(function (Form $form) {
//                        if ($form->stars>5) {
//                            $form->responseValidationMessages('stars', '最多五颗星');
//                        }
//
//                    });
                $form->select("goods_category_id", "商品类别")
                    ->options(GoodsCategory::pluck("name", "id")->toArray())
                    ->required();
                $form->tree('authors', "作家")
                    ->nodes(function () {
                        return (new AuthorModel())->allNodes();
                    })
                    ->customFormat(function ($v) {
                        if (!$v) return [];

                        // 这一步非常重要，需要把数据库中查出来的二维数组转化成一维数组
                        return array_column($v, 'id');
                    });
//
//                $form->select("author_id","所属作家")
//                    ->options(AuthorModel::pluck("name","id")->toArray());


                $form->image('img')->chunked()->uniqueName()->autoUpload();
            })->tab("状态", function (Form $form) {
                $form->switch("on_sale", "是否上架")->default(1);
                $form->switch("is_new", "是否最新")->default(0);
//                $form->switch("is_hot","是否特惠")->default(0);
                $form->switch("is_recommend", "是否推荐")->default(0);
            })->tab("相册", function (Form $form) {
                //伪造一个images的属性，否则下边多图那里上传时候会报错

                $form->model()->images = collect($form->model()->goodsImages)->pluck("img")->toArray();
                $form->multipleImage('images', "副图")
                    ->autoUpload()
//                  开启切片上传
                    ->chunked()
                    ->uniqueName();
            })->tab("介绍", function (Form $form) {
//                dd($form->model()->goodsContent->content);
                //这里必须使用下划线的这种表示方式
                $form->editor("goods_content.content", "介绍")->rules("required", [
                    "required" => "介绍必须"
                ]);
                $form->editor("goods_content.mobile_content", "手机端介绍");
            });
            $form->tab("优惠信息", function (Form $form) {
                $form->number("integral", "兑换所需积分")->default(0);
                $form->number("limit_number")
                    ->default(0)
                    ->help("仅限制积分兑换量，与秒杀无关，秒杀一律限购一件");
                $form->text("coupon_des")->help("积分兑换产品时会产生卡券，此处文字将作为卡券说明展示，默认为【持此券到店可享XX元购买（产品名）产品一件】,如产品为代金券请自行写说明");
                $form->switch("is_seckill")
                    ->default(0)
                    ->rules(function ($form) {
                        if ($form->is_seckill == 1) { //如果开启了秒杀
                            if (!$form->flash_sale_start_time || !$form->flash_sale_end_time) {
                                $form->responseValidationMessages('flash_sale_start_time', '秒杀时间区间必须');
                            }
                            if ($form->flash_sale_start_time >= $form->flash_sale_end_time) {
                                $form->responseValidationMessages('flash_sale_start_time', '秒杀开始时间和结束时间必须符合常理');
                            }
                            if ($form->flash_sale_number <= 0) {
                                $form->responseValidationMessages('flash_sale_number', '参与秒杀的商品数量必须');
                            }
                            if ($form->flash_sale_price <= 0) {
                                $form->responseValidationMessages('flash_sale_price', '参与秒杀的商品价格必须');
                            }
                        }
                    });
                $form->text("flash_sale_price", "秒杀价")->default(0);
                $form->number("flash_sale_number", "秒杀数量")->default(0);
                $form->datetimeRange("flash_sale_start_time", "flash_sale_end_time", "秒杀时间区间");
            });
//            $form->tab("优惠信息",function (Form $form){
//                $form->switch("is_hot","是否特惠")->default(0)
//                    ->rules(function ($form){
//                            if ($form->is_hot==1){
//                                if (
//                                    (!$form->promote_price||$form->promote_price=="")
//                                    &&!$form->model()->promote_price
//                                    ){
//                                    $form->responseValidationMessages('promote_price', '特惠时特惠价格必须');
//                                    }
//                            }
//                    });
//                $form->text("promote_price","特惠价");
//            });


            $images = explode(",", $form->input("images"));
//保存前先把多图属性去掉，否则保存会报错
            $form->saving(function (Form $form) {
                $form->deleteInput('images');
//                dd($form);
            });
//商品编辑完毕，对商品的图册进行处理
            $form->saved(function (Form $form) use ($images) {
                //秒杀处理，放入redis中
                $goods = $form->model();

                //在售 且秒杀 且未过期
                if ($goods->on_sale && $goods->is_seckill) {
                    $diff = $goods->flash_sale_end_time->getTimestamp() - time();
                    if ($diff > 0) {
                        Redis::setex('seckill_sku_' . $goods->id, $diff, $goods->flash_sale_number);
                    } else {
                        Redis::del('seckill_sku_' . $goods->id);
                    }
                } else {
                    Redis::del('seckill_sku_' . $goods->id);
                }

                $images = array_filter($images);
                $goods = GoodsModel::find($form->getKey());
                if ($form->input("name")) {
                    $goods->goodsImages()->whereNotIn("img", $images)->delete();
//                    GoodsImage::where("goods_id",$form->getKey())->delete();
                    //找出上传的图片与系统中图片的不同之处，求异 得出新增的图片
                    $has_sended_images = $goods->goodsImages()
                        ->select("img")
                        ->pluck("img")
                        ->toArray();
//                    dump($has_sended_images);
//                    dump($images);
                    $images_ = array_diff($images, $has_sended_images);
//                    dd($images);
                    if (count($images_) > 0) {
//                    dd($images);
                        foreach ($images_ as $k => $v) {
                            $data[] = [
                                "img" => $v,
                                'goods_id' => $form->getKey()
                            ];
                        }
//                    dump($images);
//                    dump($data);
//                    dd($data);
                        $goods->goodsImages()->createMany($data);
//                    GoodsImage::insert($data);
                    }
                }

//                return $form->location('/goods', '保存成功');
            });
        });
    }

}
